<template>
  <div class="publicpageview">
    <div class="publicformview">
      <el-form :inline="true" :model="listQuery" size="mini" ref="searchForm" label-width="100px">
        <el-row :gutter="20">


          <el-col :span="4">
            <el-form-item label="日期：" prop="incomeDate">
              <el-date-picker v-model="listQuery.queryzujindate" type="daterange" range-separator="-"
                              value-format="yyyy-MM-dd" format="yyyy-MM-dd"
                              start-placeholder="年/月/日" end-placeholder="年/月/日">
              </el-date-picker>
            </el-form-item>
          </el-col>





          <el-col :span="4">
            <div style="padding-left: 90px;">
              <el-button size="mini" type="primary" @click="handleSearch">查询</el-button>
              <el-button size="mini" @click="resetForm('searchForm')">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="publitableview">
      <!--      <el-button type="primary" size="mini" @click="handleAddUser('add')">凭证录入</el-button>-->
      <el-button type="primary" size="mini" @click="handleout">导出</el-button>
<!--      <el-button type="primary" size="mini" @click="print">打印</el-button>-->
<!--      <el-button type="danger"  icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDeletes">删除</el-button>-->

      <el-table :data="list" border fit highlight-current-row size="mini" @selection-change="handleSelectionChange">

        <!--              <el-table-column label="ID" align="center" prop="id" />-->
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="单位名称" align="center" prop="deptName" />
        <el-table-column label="代收金额" align="center" prop="dsPrice" />
        <el-table-column label="现金金额" align="center" prop="xjPrice" />
        <el-table-column label="划转金额" align="center" prop="hzPrice" />
        <el-table-column label="新华小计" align="center" prop="xhPrice" />
        <el-table-column label="pos收入" align="center" prop="posInPrice" />
        <el-table-column label="退单金额" align="center" prop="tdPrice" />
        <el-table-column label="退单手续费" align="center" prop="tdsxfPrice" />
        <el-table-column label="退货金额" align="center" prop="thPrice" />
        <el-table-column label="退货手续费" align="center" prop="thsxfPrice" />
        <el-table-column label="pos实际金额" align="center" prop="posActPrice" />
        <el-table-column label="收租小计" align="center" prop="coutZuPrice"/>
        <el-table-column label="退租金额" align="center" prop="tzPrice"/>
        <el-table-column label="合计金额" align="center" prop="coutAllPrice" />


      </el-table>
      <div class="publicpaginationview">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                       :current-page="listQuery.pageNum" background :page-sizes="[10, 20, 50, 100]"
                       :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"
                       small></el-pagination>
      </div>
    </div>




    <!-- 打印预览弹窗 -->
    <el-dialog title="打印预览" :visible.sync="printDialogVisible" width="90%" top="5vh">
      <div class="print-preview-container">
        <div class="print-header">
          <h2>银行租金收入凭证明细表</h2>
          <p>打印时间：{{ printTime }}</p>
        </div>

        <div class="print-table-container">
          <table class="print-table" border="1" cellspacing="0" cellpadding="5">
            <thead>
            <tr>
              <th>序号</th>
              <th>凭证号(收)</th>
              <th>凭证号(支)</th>
              <th>收租日期</th>
              <th>收租方式</th>
              <th>区域</th>
              <th>部门</th>
              <th>银行存款</th>
              <th>银行名称</th>
              <th>对方科目明细账</th>
              <th>租金收入</th>
              <th>借方金额</th>
              <th>贷方金额</th>
              <th>录入员</th>
              <th>录入日期</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item, index) in printData" :key="index">
              <td>{{ index + 1 }}</td>
              <td>{{ item.voucherCodeIn }}</td>
              <td>{{ item.voucherCodeOut }}</td>
              <td>{{ item.incomeDate }}</td>
              <td>{{ formatType(item.type) }}</td>
              <td>{{ item.areaName }}</td>
              <td>{{ item.deptName }}</td>
              <td>{{ item.bankCk }}</td>
              <td>{{ item.bankName }}</td>
              <td>{{ item.dfkmDetail }}</td>
              <td>{{ item.rentalIncome }}</td>
              <td>{{ item.debitAmount }}</td>
              <td>{{ item.creditAmount }}</td>
              <td>{{ item.createBy }}</td>
              <td>{{ item.createTime }}</td>
            </tr>
            </tbody>
          </table>
        </div>

        <div class="print-footer">
          <p>共 {{ printData.length }} 条记录</p>
        </div>

        <div class="print-actions">
          <el-button type="primary" @click="doPrint">确认打印</el-button>
          <el-button @click="printDialogVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import {addDetails, delDetails, listDetails, querylist, updateDetails} from "@/api/caiwu/cwRentalIncomeDetails";
import Print from "@/views/finance/dataselect/Print";
let arr = [];
let treeArr = [];

import { listResource, allocResource } from '@/api/index'
import { Message } from 'element-ui'
import { getArea, getHouseAdmin, getBlockGroup, getBlockByGroup, upload } from '@/api/common'
import { listAll } from '@/api/repair'
import moment from 'moment';
import {deleteRole} from "@/api/system";
import {blockGroupList} from "@/api/industry";
import * as XLSX from "xlsx";
import {CwDataTongji1} from "@/api/caiwu/cwTongji";
export default {
  name: "index",
  components:{Print},
  data() {
    return {
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        type:2,
        incomeDate: null,
        areaId: null,
        deptId: null,
        queryzujin1:null,
        queryzujin2:null,
        queryzujindate:[],//查询日期期间
      },

      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      total: 0,

      list: [

      ],
      dialogVisible: false,
      printDialogVisible: false,
      isAdd: 'add',
      formData: {
        type:2,
      },
      areaList: [],
      houseAdminList: [],
      houseFormAdminList: [],
      typelist:[{id:1,label:'银行'},{id:2,label:'POS'},{id:3,label:'微信'}],
      banklist:[{id:1,label:'天津银行第一中心支行'},{id:2,label:'天津银行第六中心支行'}],
      // 新增打印相关数据
      printData: [],
      printTime: ''
    };
  },

  computed: {

  },

  mounted() {
    this.getList();
    // this.getCommon();
    // this.getHouseAdmin()
    // this.getFormHouseAdmin()

  },


  methods: {

    getCommon() {
      getArea().then(res => {
        this.areaList = res.data
      })
    },

    handleQuchange(val) {
      this.listQuery.houseAdminId = null;
      if (val) {
        this.getHouseAdmin(val);

      } else {
        this.houseAdminList = [];
      }
    },

    handleFormQuchange(val) {
      this.formData.houseAdminId = null;
      if (val) {
        this.getFormHouseAdmin(val);

      } else {
        this.houseFormAdminList = [];
      }
    },

    getHouseAdmin(val) {
      getHouseAdmin({ DID: val, pageNum: 1, pageSize: 100000 }).then(res => {
        this.houseAdminList = res.data.list;
      })
    },
    getFormHouseAdmin(val) {
      getHouseAdmin({ DID: val, pageNum: 1, pageSize: 100000 }).then(res => {
        this.houseFormAdminList = res.data.list;
      })
    },

    handleSubmitClick() {
      const { formData } = this;
      if (this.isAdd == 'add') {
        console.log("add",this.formData)
        addDetails(this.formData).then(response => {
          Message({
            message:  '操作成功',
            type: "success",
            duration: 3 * 1000,
          });
          this.dialogVisible = false;
          this.getList()
        })
      }
      if (this.isAdd == 'update' || this.isAdd == 'details') {
        updateDetails(this.formData).then(response => {
          Message({
            message:  '操作成功',
            type: "success",
            duration: 3 * 1000,
          });
          this.dialogVisible = false;
          this.getList()
        })
      }

    },

    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearch() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    getList() {


      CwDataTongji1(this.listQuery).then(response=>{
        this.list = response.data.list;
        this.total = response.data.total;
      })
    },
    resetForm(val) {

      this.$refs[val].resetFields();
      this.listQuery.pageNum = 1;
    },

    handleAddUser(type) {
      this.isAdd = 'add';
      this.dialogVisible = true;
      this.formData= {
        type:2,
      }
    },

    handleClose() {
      this.resetForm("dataForm");
      this.dialogVisible = false;
    },

    async handleUpdate(currentData, type) {
      this.isAdd = type;
      this.dialogVisible = true;
      //   一定要在打开弹窗前 再赋值 不然resetFiles没用
      await this.handleFormQuchange(currentData.districtId)


      this.$nextTick(() => {
        this.formData = { ...currentData, status: String(currentData.status) };

      });
    },

    handleDelete(id) {
      this.$confirm(
          "此操作将删除该条内容，请确认是否继续操作？",
          "删除提示",
          {
            confirmButtonText: "保 存",
            cancelButtonText: "取 消",
            type: "warning",
          }
      )
          .then(() => {
            delDetails(id).then(res => {
              Message({
                message: '操作成功',
                type: "success",
                duration: 5 * 1000,
              });
              this.getList();
            })
          })
          .catch(() => { });
    },
    /** 删除按钮操作 */
    handleDeletes(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delDetails(ids);
      }).then(() => {
        this.getList();
        Message({
          message: '操作成功',
          type: "success",
          duration: 5 * 1000,
        });
      })
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    hanldetype(row){
      if(row.type==1){
        return "银行"
      }
      if(row.type==2){
        return "POS"
      }
      if(row.type==3){
        return "微信"
      }
    },
    handleout() {
      var that=this;
      this.$confirm('此操作将导出列表内容，请确认是否继续操作？', '导出提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(() => {

            querylist(this.listQuery).then((res) => {
              let list = res.data.list
              let outList = []

              res.data.list.forEach((item, index) => {
                outList.push({
                  '凭证号(收)': item.voucherCodeIn,
                  '凭证号(支)': item.voucherCodeOut,
                  收租日期: item.incomeDate,
                  收租方式:item.type==1?'银行':item.type==2?'POS':item.type==3?'微信':'',
                  区域: item.areaName,
                  部门: item.deptName,
                  银行存款: item.bankCk,
                  银行名称: item.bankName,
                  对方科目明细账: item.dfkmDetail,
                  租金收入: item.rentalIncome,
                  借方金额: item.debitAmount,
                  贷方金额: item.creditAmount,
                  录入员: item.createBy,
                  录入日期: item.createTime,

                })
              })
              // 获取表格数据
              const data = outList
              // 转换数据为工作表
              const worksheet = XLSX.utils.json_to_sheet(data)
              // 创建新的工作簿
              const workbook = XLSX.utils.book_new()
              // 将工作表添加到工作簿
              XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
              // 导出Excel文件
              XLSX.writeFile(workbook, 'POS凭证数据.xlsx')
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消导出'
            })
          })
    },


    // 修改print方法
    print(){
      // 显示加载提示
      this.$message({
        message: '正在生成打印数据...',
        type: 'info',
        duration: 2000
      });

      // 获取打印数据
      querylist(this.listQuery).then((res) => {
        this.printData = res.data.list;
        this.printTime = moment().format('YYYY-MM-DD HH:mm:ss');
        this.printDialogVisible = true;
      }).catch(error => {
        this.$message({
          message: '获取打印数据失败',
          type: 'error'
        });
        console.error('获取打印数据失败:', error);
      });
    },

    // 执行打印
    doPrint() {
      // 创建打印样式
      const printStyle = `
        <style>
          @media print {
            body { margin: 0; padding: 20px; font-family: "Microsoft YaHei", sans-serif; }
            .print-container { width: 100%; }
            .print-header { text-align: center; margin-bottom: 20px; }
            .print-header h2 { margin: 0 0 10px 0; font-size: 18px; }
            .print-header p { margin: 0; font-size: 14px; color: #666; }
            .print-table { width: 100%; border-collapse: collapse; font-size: 12px; }
            .print-table th, .print-table td { border: 1px solid #000; padding: 8px 5px; text-align: center; }
            .print-table th { background-color: #f5f5f5; font-weight: bold; }
            .print-footer { text-align: center; margin-top: 20px; font-size: 14px; }
            .no-print { display: none !important; }
          }
        </style>
      `;

      // 创建打印内容
      let printContent = `
        <div class="print-container">
          <div class="print-header">
            <h2>POS租金收入凭证明细表</h2>
            <p>打印时间：${this.printTime}</p>
          </div>
          <table class="print-table" border="1" cellspacing="0" cellpadding="5">
            <thead>
              <tr>
                <th>序号</th>
                <th>凭证号(收)</th>
                <th>凭证号(支)</th>
                <th>凭证号</th>
                <th>收租日期</th>
                <th>收租方式</th>
                <th>区域</th>
                <th>部门</th>
                <th>银行存款</th>
                <th>银行名称</th>
                <th>对方科目明细账</th>
                <th>租金收入</th>
                <th>借方金额</th>
                <th>贷方金额</th>
                <th>录入员</th>
                <th>录入日期</th>
              </tr>
            </thead>
            <tbody>
      `;

      // 添加表格数据
      this.printData.forEach((item, index) => {
        printContent += `
          <tr>
            <td>${index + 1}</td>
            <td>${item.voucherCodeIn || ''}</td>
            <td>${item.voucherCodeOut || ''}</td>
            <td>${item.incomeDate || ''}</td>
            <td>${this.formatType(item.type)}</td>
            <td>${item.areaName || ''}</td>
            <td>${item.deptName || ''}</td>
            <td>${item.bankCk || ''}</td>
            <td>${item.bankName || ''}</td>
            <td>${item.dfkmDetail || ''}</td>
            <td>${item.rentalIncome || ''}</td>
            <td>${item.debitAmount || ''}</td>
            <td>${item.creditAmount || ''}</td>
            <td>${item.createBy || ''}</td>
            <td>${item.createTime || ''}</td>
          </tr>
        `;
      });

      printContent += `
            </tbody>
          </table>
          <div class="print-footer">
            <p>共 ${this.printData.length} 条记录</p>
          </div>
        </div>
      `;

      // 创建打印窗口
      const printWindow = window.open('', '_blank');
      printWindow.document.write(`
        <html>
          <head>
            <title>POS凭证数据打印</title>
            ${printStyle}
          </head>
          <body>
            ${printContent}
          </body>
        </html>
      `);
      printWindow.document.close();

      // 等待内容加载完成后打印
      printWindow.onload = function() {
        printWindow.print();
        // 打印后关闭窗口
        setTimeout(() => {
          printWindow.close();
        }, 500);
      };

      // 关闭打印预览弹窗
      this.printDialogVisible = false;
    },

    // 格式化类型
    formatType(type) {
      if(type == 1) return "银行";
      if(type == 2) return "POS";
      if(type == 3) return "微信";
      return "";
    }
  },
};
</script>

<style scoped>
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 180px;
}

::v-deep .el-dialog__body {
  padding: 30px 0;

}

.tableView {
  width: 100%;
  background: #F7F7F7;
  padding-top: 20px;
  padding-bottom: 20px;

.title {

  font-family: SourceHanSansSC, SourceHanSansSC;
  font-weight: bold;
  font-size: 16px;
  color: #008C93;
  text-align: center;
  font-style: normal;
  text-transform: none;
}

.el-row {
  text-align: center;
  height: 50px;
  line-height: 50px;
  border: 1px solid #E9E9E9;
  background: #fff;

.el-col {
  height: 50px;
  border-right: 1px solid #E9E9E9;
}

.el-col:last-of-type {
  border-right: none;
}
}

.el-row:first-of-type {
  border-bottom: none;
  background: none;
}

.el-row:last-of-type {
  border-top: none;

.el-col {
  text-align: left;
  padding-left: 58px;
}
}

.el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
  margin-bottom: 0;
}

::v-deep .el-form-item--mini .el-form-item__content,
.el-form-item--mini .el-form-item__label {
  line-height: 50px;
}



}
</style>
